package com.aiti.lulian.controller;

import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import com.aiti.base.core.base.controller.WebController;
import com.aiti.base.core.utils.message.Message;
import com.aiti.lulian.dto.CustomerManagementDto;
import com.aiti.lulian.dto.CustomerTagDto;
import com.aiti.lulian.dto.CustomerTagGroupDto;
import com.aiti.lulian.entity.CustomerManagement;
import com.aiti.lulian.entity.LuLianEnterprise;
import com.aiti.lulian.entity.LuLianEnterpriseHistory;
import com.aiti.lulian.entity.LuLianEnterpriseUser;
import com.aiti.lulian.entity.excel.CustomerManagementExcelExport;
import com.aiti.lulian.entity.excel.CustomerManagementPublicExcelExport;
import com.aiti.lulian.handler.HeaderStyleHandler;
import com.aiti.lulian.mapper.LuLianEnterpriseHistoryMapper;
import com.aiti.lulian.mapper.LuLianEnterpriseUserMapper;
import com.aiti.lulian.service.*;
import com.aiti.lulian.vo.CustomerManagementVo;
import com.aiti.lulian.vo.CustomerTagVo;
import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.net.HttpHeaders;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/customerManagement")
@Api(tags = "客户管理控制层", description = "客户管理")
public class CustomerManagementController extends WebController {
    protected final Logger logger = LoggerFactory.getLogger(CustomerManagementController.class);

    @Autowired
    private ICustomerManagementService customerManagementService;

    @Autowired
    private ILuLianEnterpriseUserService enterpriseUserService;


    @Autowired
    private ILulianEnterpriseHistoryService enterpriseHistoryService;

    @Autowired
    private ILuLianEnterpriseService luLianEnterpriseService;

    @Autowired
    private LuLianEnterpriseHistoryMapper luLianEnterpriseHistoryMapper;

    @Autowired
    private LuLianEnterpriseUserMapper luLianEnterpriseUserMapper;

    @Autowired
    private ICustomerTagGroupService customerTagGroupService;

    @Autowired
    private ICustomerTagService customerTagService;

    //客户列表-分页
    @ApiOperation(value = "客户列表-分页")
    @GetMapping("findCustomerListPage")
    public Message findCustomerListPage(CustomerManagementDto customerManagementDto) {
        try {
            //检查当前是否为已登录状态
            String userId = findUserId();
            if (StrUtil.isBlank(userId)) {
                System.out.println("------------------未登录------------------");
                return Fail("请先注册/登录！");
            }
            //检查是否为已认证企业的账号
            LambdaQueryWrapper<LuLianEnterpriseUser> enterpriseUserWrapper = new LambdaQueryWrapper<>();
            enterpriseUserWrapper.eq(LuLianEnterpriseUser::getUserId, userId);
            List<LuLianEnterpriseUser> enterpriseUserList = enterpriseUserService.list(enterpriseUserWrapper);
            List<String> enterpriseIds = enterpriseUserList.stream().map(LuLianEnterpriseUser::getEnterpriseId).collect(Collectors.toList());
            if (enterpriseIds == null || enterpriseIds.size() == 0) {
                enterpriseIds.add("0");
            }
            LambdaQueryWrapper<LuLianEnterpriseHistory> enterpriseHistoryWrapper = new LambdaQueryWrapper<>();
            enterpriseHistoryWrapper.in(LuLianEnterpriseHistory::getBaseId, enterpriseIds);
            int count = enterpriseHistoryService.count(enterpriseHistoryWrapper);
            if (count == 0) {
                return Fail("该账号未认证企业，请先进行企业认证！");
            } else if (count > 1) {
                return Fail("该账号关联了多个认证企业！");
            } else if (count == 1 && enterpriseUserList.size() > 1) {
                return Fail("该账号的企业关联记录存在多条！");
            }
            Integer pageSize = customerManagementDto.getPageSize();
            Integer pageNum = customerManagementDto.getPageNum();
            Page<CustomerManagement> page = startPage(pageNum, pageSize);
            List<CustomerManagementVo> list = customerManagementService.findCustomerListPage(page, customerManagementDto, userId);
            return Success(getPageResult(list, pageNum, pageSize, (int) page.getTotal()));
        } catch (Exception e) {
            logger.error("查询异常：===》" + e);
            return Fail(e.getMessage());
        }
    }


    /**
     * 新增客户
     */
    @ApiOperation(value = "新增客户")
    @PostMapping("addCustomer")
    public Message addCustomer(@RequestBody CustomerManagementDto customerManagementDto) {
        try {
            if (customerManagementDto == null) {
                logger.error("新增异常：===》入参异常");
                return Message.fail("入参异常");
            }
//            //检查当前是否为已登录状态
//            String userId = findUserId();
//            if (StrUtil.isBlank(userId)) {
//                System.out.println("------------------未登录------------------");
//                return Fail("请先注册/登录！");
//            }
            //检查是否为已认证企业的账号
            LambdaQueryWrapper<LuLianEnterpriseUser> enterpriseUserWrapper = new LambdaQueryWrapper<>();
            enterpriseUserWrapper.eq(LuLianEnterpriseUser::getUserId, customerManagementDto.getCreator());
            List<LuLianEnterpriseUser> enterpriseUserList = enterpriseUserService.list(enterpriseUserWrapper);
            List<String> enterpriseIds = enterpriseUserList.stream().map(LuLianEnterpriseUser::getEnterpriseId).collect(Collectors.toList());
            if (enterpriseIds == null || enterpriseIds.size() == 0) {
                enterpriseIds.add("0");
            }
            LambdaQueryWrapper<LuLianEnterprise> enterpriseWrapper = new LambdaQueryWrapper<>();
            enterpriseWrapper.in(LuLianEnterprise::getBaseId, enterpriseIds);
            int count = luLianEnterpriseService.count(enterpriseWrapper);
            if (count == 0) {
                return Fail("该账号未认证企业，请先进行企业认证");
            } else if (count > 1) {
                return Fail("该账号关联了多个认证企业");
            } else if (count == 1 && enterpriseUserList.size() > 1) {
                return Fail("该账号的企业关联记录存在多条");
            }
            // 判断客户的公司名称是否重复
            LambdaQueryWrapper<CustomerManagement> customerManagementWrapper = new LambdaQueryWrapper<>();
            customerManagementWrapper.eq(CustomerManagement::getEnterpriseName, customerManagementDto.getEnterpriseName());
            int customerCount = customerManagementService.count(customerManagementWrapper);
            if (customerCount > 0) {
                return Fail("该公司名称已存在");
            }
            // 新增客户信息
            return customerManagementService.addCustomer(customerManagementDto);
        } catch (Exception e) {
            logger.error("新增异常：===》" + e);
            return Error(e.getMessage());
        }
    }

    /**
     * 客户信息回显
     */
    @ApiOperation(value = "客户信息回显")
    @GetMapping("getCustomerById")
    public Message getCustomerById(@RequestParam("baseId") String baseId) {
        try {
            CustomerManagementVo customerManagementVo = customerManagementService.getCustomerById(baseId);
            return Success(customerManagementVo);
        } catch (Exception e) {
            logger.error("查询异常：===》" + e);
            return Error(e.getMessage());
        }
    }

    /**
     * 修改客户
     */
    @ApiOperation(value = "修改客户")
    @PutMapping("updateCustomer")
    public Message updateCustomer(@RequestBody CustomerManagementDto customerManagementDto) {
        try {
            if (customerManagementDto == null) {
                logger.error("修改异常：===》入参异常");
                return Fail("入参异常");
            }
//            // 若能修改公司名称，则判断客户的公司名称是否重复
//            LambdaQueryWrapper<CustomerManagement> customerManagementWrapper = new LambdaQueryWrapper<>();
//            customerManagementWrapper.eq(CustomerManagement::getEnterpriseName, customerManagementDto.getEnterpriseName());
//            int customerCount = customerManagementService.count(customerManagementWrapper);
//            if (customerCount > 1) {
//                return Fail("该公司名称已存在");
//            }
            // 修改客户信息
            return customerManagementService.updateCustomer(customerManagementDto);
        } catch (Exception e) {
            logger.error("修改异常：===》" + e);
            return Fail(e.getMessage());
        }
    }

    /**
     * 转交客户（支持批量）
     */
    @ApiOperation(value = "转交客户（支持批量）")
    @PutMapping("forwardCustomer")
    public Message forwardCustomer(@RequestBody CustomerManagementDto customerManagementDto) {
        try {
            return customerManagementService.forwardCustomer(customerManagementDto);
        } catch (Exception e) {
            logger.error("修改异常：===》" + e);
            return Fail(e.getMessage());
        }
    }

    /**
     * 删除客户（支持批量）
     */
    @ApiOperation("删除客户（支持批量）")
    @DeleteMapping("/deleteCustomer")
    public Message deleteCustomer(@RequestParam("baseIds") String[] baseIds) {
        try {
            return customerManagementService.removeCustomerByBaseIds(baseIds);
        } catch (Exception e) {
            logger.error("删除异常：===》" + e);
            return Error(e.getMessage());
        }
    }

    @ApiOperation(value = "客户信息逻辑删除")
    @PostMapping("updateCustomerById")
    public Message updateCustomerById(String baseId) {
        try {
            // 修改客户信息(隐藏客户信息)
            int res = customerManagementService.updateCustomerById(baseId);
            if (res > 0) {
                return Message.success();
            } else {
                return Message.fail();
            }
        } catch (Exception e) {
            logger.error("修改异常：===》" + e);
            return Message.fail(e.getMessage());
        }
    }

    /***
     * 获取员工客户数量
     * @return
     */
    @GetMapping("/getCustomerCountByEmployee")
    public Message getCustomerCountByEmployee(CustomerManagementDto dto) {
        String userId = findUserId();
        String roleIds = dto.getRoleIds();
        if (StringUtils.isBlank(roleIds)) {
            return Message.fail("没有查询到当前用户的角色");
        }

        String[] idArgs = roleIds.split(",");
        //企业用户分支
        String enterpriseId = "";
        if (ArrayUtil.containsAny(idArgs, "8836c75af939406a9f41128826f6d8b3")) {
            //查询员工所对应的企业
            List<LuLianEnterpriseUser> enterpriseUserList = luLianEnterpriseUserMapper.selectList(new QueryWrapper<LuLianEnterpriseUser>().eq("user_id", userId));
            if (enterpriseUserList == null || enterpriseUserList.size() != 1) {
                return Message.fail("查询到的用户所对应企业信息数据异常");
            }
            LuLianEnterpriseUser luLianEnterpriseUser = enterpriseUserList.get(0);
            LuLianEnterprise enterprise = luLianEnterpriseService.getById(luLianEnterpriseUser.getEnterpriseId());
            //LuLianEnterpriseHistory luLianEnterpriseHistory = luLianEnterpriseHistoryMapper.selectById(luLianEnterpriseUser.getEnterpriseId());
            if (enterprise == null) {
                return Message.fail("查询到的用户所对应企业信息数据异常");
            }
            enterpriseId = luLianEnterpriseUser.getEnterpriseId();
        } else if (ArrayUtil.containsAny(idArgs, "24d3f470d5784d2ba5f11f70f0b66af5")) {
            // 无需操作  如果需求可在这里增加代码
        } else {
            return Message.fail("用户角色不正确");
        }


        Integer pageSize = dto.getPageSize();
        Integer pageNum = dto.getPageNum();
        Page<List<Map>> page = this.startPage(pageNum, pageSize);
        List<Map> list = customerManagementService.getCustomerCountByEmployee(page, enterpriseId, userId);
        return Message.success(getPageResult(list, pageNum, pageSize, (int) page.getTotal()));
    }

    /***
     * 查询客户总数
     * @return
     */
    @GetMapping("/getCustomTotal")
    public Message getCustomTotal(CustomerManagementDto dto) {
        String userId = findUserId();
        String roleIds = dto.getRoleIds();
        if (StringUtils.isBlank(roleIds)) {
            return Message.fail("没有查询到当前用户的角色");
        }

        String[] idArgs = roleIds.split(",");
        //企业用户分支
        String enterpriseId = "";
        if (ArrayUtil.containsAny(idArgs, "8836c75af939406a9f41128826f6d8b3")) {
            //查询员工所对应的企业
            List<LuLianEnterpriseUser> enterpriseUserList = luLianEnterpriseUserMapper.selectList(new QueryWrapper<LuLianEnterpriseUser>().eq("user_id", userId));
            if (enterpriseUserList == null || enterpriseUserList.size() != 1) {
                return Message.fail("查询到的用户所对应企业信息数据异常");
            }
            LuLianEnterpriseUser luLianEnterpriseUser = enterpriseUserList.get(0);
            LuLianEnterprise enterprise = luLianEnterpriseService.getById(luLianEnterpriseUser.getEnterpriseId());
            //LuLianEnterpriseHistory luLianEnterpriseHistory = luLianEnterpriseHistoryMapper.selectById(luLianEnterpriseUser.getEnterpriseId());
            if (enterprise == null) {
                return Message.fail("查询到的用户所对应企业信息数据异常");
            }
            enterpriseId = luLianEnterpriseUser.getEnterpriseId();
        } else if (ArrayUtil.containsAny(idArgs, "24d3f470d5784d2ba5f11f70f0b66af5")) {
            // 无需操作  如果需求可在这里增加代码
        } else {
            return Message.fail("用户角色不正确");
        }

        Map customTotal = customerManagementService.getCustomTotal(enterpriseId, userId);
        return Message.success(customTotal);
    }

    /**
     * 查询该企业下的客户
     *
     * @param enterpriseId 企业Id
     * @return
     */
    @GetMapping("/queryClientOnEnterpriseId")
    public Message queryClientOnEnterpriseId(@RequestParam(value = "enterpriseId", required = true) String enterpriseId) {
        LambdaQueryWrapper<CustomerManagement> lqw = new LambdaQueryWrapper<CustomerManagement>();
        lqw.eq(CustomerManagement::getCompanyId, enterpriseId).eq(CustomerManagement::getIsDel, "0");
        lqw.select(CustomerManagement::getBaseId, CustomerManagement::getContacts);
        List<CustomerManagement> list = customerManagementService.list(lqw);
        return Message.success(list);
    }

    /**
     * 查询客户列表
     * customerManagementDto.companyId 企业ID
     * customerManagementDto.creator 用户ID（当登录人为企业管理员时，该参数为null，即查询该企业下的所有客户）
     */
    @ApiOperation("查询客户列表")
    @GetMapping("/getCustomerList")
    public Message getCustomerList(CustomerManagementDto customerManagementDto) {
        try {
            Integer pageNum = customerManagementDto.getPageNum();
            Integer pageSize = customerManagementDto.getPageSize();
            Page<CustomerManagementVo> page = startPage(pageNum, pageSize);
            List<CustomerManagementVo> customerVoList = customerManagementService.getCustomerList(customerManagementDto, page);
            return Success(getPageResult(customerVoList, pageNum, pageSize, page.getTotal()));
        } catch (Exception e) {
            logger.error("查询异常：===》" + e);
            return Error(e.getMessage());
        }
    }

    @ApiOperation("新增或编辑标签组")
    @PostMapping("/tag/group/addOrUpdate")
    public Message addOrUpdateTagGroup(@RequestBody CustomerTagGroupDto customerTagGroupDto) {
        if (StrUtil.isBlank(customerTagGroupDto.getUserId())) {
            return Fail("请先登录");
        }
        return customerTagGroupService.addOrUpdateTagGroup(customerTagGroupDto);
    }

    @ApiOperation("删除标签组")
    @DeleteMapping("/tag/group")
    public Message deleteTagGroup(CustomerTagGroupDto customerTagGroupDto) {
        if (StrUtil.isBlank(customerTagGroupDto.getUserId())) {
            return Fail("请先登录");
        }
        return customerTagGroupService.deleteTagGroup(customerTagGroupDto);
    }

    @ApiOperation("查询企业下的标签组列表")
    @GetMapping("/tag/group/list")
    public Message getTagGroupList(CustomerTagGroupDto customerTagGroupDto) {
        String userId = customerTagGroupDto.getUserId();
        if (StrUtil.isBlank(userId)) {
            userId = findUserId();
            if (StrUtil.isBlank(userId)) {
                return Fail("请先登录");
            }
            customerTagGroupDto.setUserId(userId);
        }
        return customerTagGroupService.getTagGroupList(customerTagGroupDto);
    }

    @ApiOperation("查询标签组详情")
    @GetMapping("/tag/group/details")
    public Message getTagGroupDetails(@RequestParam("baseId") String baseId,
                                      @RequestParam("userId") String userId) {
        if (StrUtil.isBlank(userId)) {
            return Fail("请先登录");
        }
        return customerTagGroupService.getTagGroupDetails(baseId);
    }

    @ApiOperation("新增或编辑标签")
    @PostMapping("/tag/addOrUpdate")
    public Message addOrUpdateTag(@RequestBody CustomerTagDto customerTagDto) {
        if (StrUtil.isBlank(customerTagDto.getUserId())) {
            return Fail("请先登录");
        }
        return customerTagService.addOrUpdateTag(customerTagDto);
    }

    @ApiOperation("删除标签")
    @DeleteMapping("/tag")
    public Message deleteTag(CustomerTagDto customerTagDto) {
        if (StrUtil.isBlank(customerTagDto.getUserId())) {
            return Fail("请先登录");
        }
        return customerTagService.deleteTag(customerTagDto);
    }

    @ApiOperation("查询标签列表")
    @GetMapping("/tag/list")
    public Message getTagList(CustomerTagDto customerTagDto) {
        String userId = customerTagDto.getUserId();
        if (StrUtil.isBlank(userId)) {
            userId = findUserId();
            if (StrUtil.isBlank(userId)) {
                return Fail("请先登录");
            }
            customerTagDto.setUserId(userId);
        }
        return customerTagService.getTagList(customerTagDto);
    }

    @ApiOperation("查询全部标签列表")
    @GetMapping("/tags")
    public Message getTags(CustomerTagDto customerTagDto) {
        String userId = customerTagDto.getUserId();
        if (StrUtil.isBlank(userId)) {
            userId = findUserId();
            if (StrUtil.isBlank(userId)) {
                return Fail("请先登录");
            }
            customerTagDto.setUserId(userId);
        }
        return customerTagService.getTags(customerTagDto);
    }

    @ApiOperation("查询标签详情")
    @GetMapping("/tag/details")
    public Message getTagDetails(@RequestParam("baseId") String baseId,
                                 @RequestParam("userId") String userId) {
        if (StrUtil.isBlank(userId)) {
            return Fail("请先登录");
        }
        return customerTagService.getTagDetails(baseId);
    }

    @ApiOperation("新增客户2.0")
    @PostMapping("/customer")
    public Message saveCustomer(@RequestBody CustomerManagementDto customerManagementDto) {
        if (StrUtil.isBlank(customerManagementDto.getUserId())) {
            return Fail("请先登录");
        }
        //必填项校验
        if (StrUtil.isBlank(customerManagementDto.getEnterpriseName())//客户名称
                || StrUtil.isBlank(customerManagementDto.getCustomerType())//客户类型
                || StrUtil.isBlank(customerManagementDto.getProvince())//省
                || StrUtil.isBlank(customerManagementDto.getCity())//市
                || StrUtil.isBlank(customerManagementDto.getLinkWayOne())) {//联系方式一
            return Fail("请检查必填项是否已填写");
        }
        return customerManagementService.saveCustomer(customerManagementDto);
    }

    @ApiOperation("查询客户详情2.0")
    @GetMapping("/customer")
    public Message getCustomerDetails(CustomerManagementDto customerManagementDto) {
        if (StrUtil.isBlank(customerManagementDto.getUserId())) {
            return Fail("请先登录");
        }
        return customerManagementService.getCustomerDetails(customerManagementDto);
    }

    @ApiOperation("编辑单个客户2.0")
    @PutMapping("/customer")
    public Message editCustomer(@RequestBody CustomerManagementDto customerManagementDto) {
        if (StrUtil.isBlank(customerManagementDto.getUserId())) {
            return Fail("请先登录");
        }
        return customerManagementService.editCustomer(customerManagementDto);
    }

    @ApiOperation("批量编辑客户")
    @PutMapping("/customer/batch")
    public Message editCustomerBatch(@RequestBody CustomerManagementDto customerManagementDto) {
        if (StrUtil.isBlank(customerManagementDto.getUserId())) {
            return Fail("请先登录");
        }
        return customerManagementService.editCustomerBatch(customerManagementDto);
    }

    @ApiOperation("编辑协作人")
    @PutMapping("/collaborator")
    public Message editCollaborator(@RequestBody CustomerManagementDto customerManagementDto) {
        if (StrUtil.isBlank(customerManagementDto.getUserId())) {
            return Fail("请先登录");
        }
        return customerManagementService.editCollaborator(customerManagementDto);
    }

    @ApiOperation("查询客户的协作人列表（支持多客户）")
    @GetMapping("/collaborator/list")
    public Message getCollaboratorList(@RequestParam("customerIds") List<String> customerIds,
                                       @RequestParam("userId") String userId) {
        if (StrUtil.isBlank(userId)) {
            return Fail("请先登录");
        }
        return customerManagementService.getCollaboratorList(customerIds);
    }

    @ApiOperation("下载客户导入模板")
    @GetMapping("/customer/template/download")
    public Message downloadCustomerTemplate(@RequestParam("userId") String userId,
                                            HttpServletResponse response) {
        FileInputStream fileInputStream = null;
        ServletOutputStream outputStream = null;
        try {
            if (StrUtil.isBlank(userId)) {
                return Fail("请先登录");
            }
            // 设置文件路径
            String filePath = "/home/services/apache-tomcat-9.0.34-8061/webapps/ROOT/file/客户导入模板.xlsx";
//            String filePath = "C:\\Users\\Administrator\\Desktop\\客户导入模板.xlsx";
            File downloadFile = new File(filePath);

            // 设置文件名（响应头中的推荐文件名）
            String fileName = "客户导入模板.xlsx";

            // 对文件名进行URL编码
            String encodedFileName = URLEncoder.encode(fileName, "UTF-8").replaceAll("\\+", "%20");

            // 设置响应头
            response.setContentType("application/octet-stream");
//            response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
            response.setHeader("Content-Disposition", "attachment; filename=\"" + encodedFileName + "\"; filename*=UTF-8''" + encodedFileName);

            // 设置文件大小
            response.setContentLength((int) downloadFile.length());

            // 通过文件输入流读取文件内容
            fileInputStream = new FileInputStream(downloadFile);

            // 通过ServletOutputStream将文件内容写入HTTP响应
            outputStream = response.getOutputStream();
            byte[] buffer = new byte[4096];
            int bytesRead;

            while ((bytesRead = fileInputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }

            // 关闭流资源
            if (fileInputStream != null) {
                fileInputStream.close();
            }
            if (outputStream != null) {
                outputStream.close();
            }

            return Success();
        } catch (Exception e) {
            logger.error("下载模板异常：===》" + e);
            return Fail(e.getMessage());
        }
    }

    /**
     * @param mode 处理客户名称重复数据的模式：'1'：不导入（跳过该条信息）；'2'：覆盖导入（删除原客户信息，录入新客户信息）
     */
    @ApiOperation("批量导入客户数据")
    @PostMapping("/customer/import")
    public Message importCustomerBatch(@RequestPart("file") MultipartFile file,
                                       @RequestParam("mode") String mode,
                                       @RequestParam("enterpriseId") String enterpriseId,
                                       @RequestParam("userId") String userId,
                                       @RequestParam(value = "isPublic", required = false) String isPublic,
                                       @RequestParam(value = "deptId", required = false) String deptId) {
        try {
            if (StrUtil.isBlank(userId)) {
                return Fail("请先登录");
            }
            if (StrUtil.isBlank(enterpriseId)) {
                return Fail("当前用户未关联企业");
            }
            if (file == null) {
                return Fail("请上传文件");
            }
            String contentType = file.getContentType();
            String originalFilename = file.getOriginalFilename();
            if (! ("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet".equals(contentType)
                    && originalFilename != null && originalFilename.endsWith(".xlsx"))) {
                return Fail("请上传xlsx格式的文件");
            }
            return customerManagementService.importCustomerBatch(file, mode, enterpriseId, userId, deptId, isPublic);
        } catch (Exception e) {
            logger.error("导入异常：===》" + e);
            return Fail(e.getMessage());
        }
    }

    @ApiOperation("导出客户数据")
    @GetMapping("/customer/export")
    public Message exportCustomer(HttpServletResponse response,
                                  CustomerManagementDto customerManagementDto) {
        try {
            if (StrUtil.isBlank(customerManagementDto.getUserId())) {
                return Fail("请先登录");
            }
            List<CustomerManagementVo> customerManagementVos = customerManagementService.getCustomerList(customerManagementDto, null);
            //准备要导出的数据列表
            List<CustomerManagementVo> customerDataList = customerManagementVos.stream().peek(i -> i.setTagStr(i.getTags().stream().map(CustomerTagVo::getTagName).collect(Collectors.joining(",")))).collect(Collectors.toList());
            List collect;
            if (StrUtil.equals(customerManagementDto.getIsPublic(), "1")) {
                collect = customerDataList.stream().map(i -> {
                    CustomerManagementPublicExcelExport customerManagementPublicExcelExport = new CustomerManagementPublicExcelExport();
                    BeanUtils.copyProperties(i, customerManagementPublicExcelExport);
                    return customerManagementPublicExcelExport;
                }).collect(Collectors.toList());
            } else {
                collect = customerDataList.stream().map(i -> {
                    CustomerManagementExcelExport customerManagementExcelExport = new CustomerManagementExcelExport();
                    BeanUtils.copyProperties(i, customerManagementExcelExport);
                    return customerManagementExcelExport;
                }).collect(Collectors.toList());
            }

            // 设置响应头，确保浏览器以下载方式处理文件
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");

            // 设置文件名，注意需要对中文进行 URL 编码
            String fileName = URLEncoder.encode("客户", "UTF-8").replaceAll("\\+", "%20");
            response.setHeader(HttpHeaders.CONTENT_DISPOSITION,
                    "attachment; filename=\"" + fileName + ".xlsx\";" +
                            " filename*=UTF-8''" + fileName + ".xlsx");

            // 使用 EasyExcel 写入数据到输出流
            OutputStream outputStream =  response.getOutputStream();
                EasyExcel.write(outputStream, StrUtil.equals(customerManagementDto.getIsPublic(), "1") ? CustomerManagementPublicExcelExport.class : CustomerManagementExcelExport.class)
                        .sheet("客户")
                        .registerWriteHandler(new HeaderStyleHandler())
                        .doWrite(collect);

            // 关闭流资源
            if (outputStream != null) {
                outputStream.close();
            }

            return Success();
        } catch (Exception e) {
            logger.error("导出异常：===》" + e);
            return Fail(e.getMessage());
        }
    }

    @ApiOperation("修改联系人")
    @PutMapping("/contact")
    public Message updateContact(@RequestBody CustomerManagementDto customerManagementDto) {
        String userId = customerManagementDto.getUserId();
        if (StrUtil.isBlank(userId)) {
            userId = findUserId();
            if (StrUtil.isBlank(userId)) {
                return Fail("请先登录");
            }
            customerManagementDto.setUserId(userId);
        }
        return customerManagementService.updateContact(customerManagementDto);
    }

    @ApiOperation("查询客户的跟进记录列表")
    @GetMapping("/follow/list")
    public Message getFollowListByCustomerId(@RequestParam("customerId") String customerId,
                                 @RequestParam(value = "userId", required = false) String userId) {
        if (StrUtil.isBlank(userId)) {
            userId = findUserId();
            if (StrUtil.isBlank(userId)) {
                return Fail("请先登录");
            }
        }
        return customerManagementService.getFollowListByCustomerId(customerId);
    }
}